package com.jumper.study.admin.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jumper.study.admin.dto.req.RoleReq;
import com.jumper.study.admin.dto.resp.RoleResp;
import com.jumper.study.admin.service.RoleService;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.db.model.Role;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;



@RestController
@RequestMapping("/api/backend/roles")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("")
    public CommonResult<List<RoleResp>> getList() {
        List<RoleResp> roleList = roleService.list().stream()
                    .map(r -> new RoleResp(r.getId(), r.getTitle(), r.getMenus(), r.getCreatedAt()))
                    .toList();

        return CommonResult.success(roleList);
    }

    @GetMapping("/{id}")
    public CommonResult<Object> getItem(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        RoleResp resp = new RoleResp(role.getId(), role.getTitle(), role.getMenus(), role.getCreatedAt());

        return CommonResult.success(resp);
    }
    
    @PostMapping("/")
    public CommonResult<Boolean> create(@RequestBody @Validated RoleReq req) {
        Role role = new Role();
        role.setId(0);
        role.setTitle(req.getTitle());
        role.setMenus(req.getMenus());
        boolean result = roleService.save(role);
        
        return CommonResult.success(result);
    }
    
    @PostMapping("/{id}")
    public CommonResult<Boolean> update(@PathVariable Integer id, @RequestBody @Validated RoleReq req) {
        Role role = roleService.getById(id);
        if (role == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        role.setTitle(req.getTitle());
        role.setMenus(req.getMenus());
        boolean result = roleService.updateById(role);
        
        return CommonResult.success(result);
    }
    
    @DeleteMapping("/{id}")
    public CommonResult<Boolean> delete(@PathVariable Integer id) {
        boolean result = roleService.removeById(id);

        return CommonResult.success(result);
    }
}
